<?
/**
 * Interface for MySQL database
 * Class is Singleton, preserving one connection per session.
 * 
 * Note! This is a PHP4 compatible version of Alexanders original PHP5 class.
 */
require_once("config.php");
class Database {
	
	var $username; 
	var $password;
	var $host;
	var $database;
	
	var $connection = null;
	var $instance = null;
	
	
	/**
	 * Establish connection to MySQL database
	 */
	private function Database() {
		$this->setConfig();
		$this->connection = mysql_connect($this->host, $this->username, $this->password);
		Database::charsetFix();

		if($this->connection == false) {
			trigger_error("Could not connect to database.", E_USER_ERROR);
		}
		return $this;
	}
	
	private function setConfig() {
	    GLOBAL $CONFIG;
		$config = parse_ini_file("dbConfig.ini", true);
		if(! $config or empty($config)) {
			throw new Exception("Could not parse configuration file.", E_ERROR);
		}
		
		$config = $config[$CONFIG['environment']];
		$this->username = $config['username'];
		$this->password = $config['password'];
		$this->host = $config['host'];
		$this->database = $config['database'];
	}
	
	
	public function getInstance() {
        static $instance;
        if(!isset($instance)) {
            $instance = new Database();
        }
        return $instance;
	}
	
	public function query($sql, $database = null, $throw_error = true) {
		if($database === null) {
			$database = $this->database;
		}
		mysql_select_db($database, $this->getConnection());
		if($throw_error) {
		    $query = mysql_query($sql, $this->getConnection());
		    $mysql_error = mysql_error($this->getConnection());
            if(!empty($mysql_error)) {
                throw new Exception("mysql error: ".mysql_error());
            }
        } else {
          $query = mysql_query($sql, $this->getConnection());
        }
        return $query;
    }
    
    private function getConnection() {
        if($this->connection === null) {
            trigger_error("Connection to database not established.", E_USER_ERROR);
        }
        return $this->connection;
    }
    
    private function charsetFix() {
        // BIG thanks to http://www.adviesenzo.nl/examples/php_mysql_charset_fix/
        $db_charset = Database::query( "SHOW VARIABLES LIKE 'character_set_database'" );
        $charset_row = mysql_fetch_assoc( $db_charset );
        mysql_query( "SET NAMES '" . $charset_row['Value'] . "'" );
    }
}
